package com.example.app01

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.activity.OnBackPressedCallback
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import de.hdodenhof.circleimageview.CircleImageView
import java.io.File
import java.io.FileOutputStream
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

class MainActivity : AppCompatActivity() {

    private lateinit var ivPlayerAvatar: CircleImageView
    private lateinit var tvPlayerName: TextView
    private lateinit var tvPlayerGender: TextView
    private lateinit var tvPlayerPhone: TextView
    private lateinit var tvHighScore: TextView
    private lateinit var btnTakePhoto: Button
    private lateinit var btnEditInfo: Button
    private lateinit var btnStartGame: Button

    private var playerName: String = "魏健"
    private var playerGender: String = "男"
    private var playerPhone: String = "13800138000"
    private var highScore: Int = 0
    private var backPressedTime: Long = 0
    private var currentPhotoPath: String = ""

    private val cameraPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) { isGranted ->
        if (isGranted) {
            showPhotoSourceDialog()
        } else {
            Toast.makeText(this, "需要相机权限才能拍照", Toast.LENGTH_SHORT).show()
        }
    }

    private val cameraLauncher = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { result ->
        if (result.resultCode == Activity.RESULT_OK) {
            // 处理拍照结果
            val bitmap = BitmapFactory.decodeFile(currentPhotoPath)
            ivPlayerAvatar.setImageBitmap(bitmap)
            saveAvatarToInternalStorage(bitmap)
            Toast.makeText(this, "照片已保存", Toast.LENGTH_SHORT).show()
        }
    }

    private val galleryLauncher = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { result ->
        if (result.resultCode == Activity.RESULT_OK) {
            result.data?.data?.let { uri ->
                try {
                    val inputStream = contentResolver.openInputStream(uri)
                    val bitmap = BitmapFactory.decodeStream(inputStream)
                    ivPlayerAvatar.setImageBitmap(bitmap)
                    saveAvatarToInternalStorage(bitmap)
                    Toast.makeText(this, "照片已设置", Toast.LENGTH_SHORT).show()
                } catch (e: Exception) {
                    Toast.makeText(this, "设置照片失败", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        initViews()
        setupClickListeners()
        setupBackPressHandler()
        loadAvatarFromInternalStorage()
        updatePlayerInfo()
    }

    private fun initViews() {
        ivPlayerAvatar = findViewById(R.id.ivPlayerAvatar)
        tvPlayerName = findViewById(R.id.tvPlayerName)
        tvPlayerGender = findViewById(R.id.tvPlayerGender)
        tvPlayerPhone = findViewById(R.id.tvPlayerPhone)
        tvHighScore = findViewById(R.id.tvHighScore)
        btnTakePhoto = findViewById(R.id.btnTakePhoto)
        btnEditInfo = findViewById(R.id.btnEditInfo)
        btnStartGame = findViewById(R.id.btnStartGame)
    }

    private fun setupClickListeners() {
        btnTakePhoto.setOnClickListener {
            checkCameraPermission()
        }

        btnEditInfo.setOnClickListener {
            val intent = Intent(this, EditInfoActivity::class.java)
            intent.putExtra("name", playerName)
            intent.putExtra("gender", playerGender)
            intent.putExtra("phone", playerPhone)
            startActivityForResult(intent, REQUEST_EDIT_INFO)
        }

        btnStartGame.setOnClickListener {
            val intent = Intent(this, GameActivity::class.java)
            intent.putExtra("playerName", "$playerName$playerPhone".take(15)) // 限制长度
            startActivityForResult(intent, REQUEST_GAME)
        }

        ivPlayerAvatar.setOnClickListener {
            checkCameraPermission()
        }
    }

    private fun checkCameraPermission() {
        when {
            ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.CAMERA
            ) == PackageManager.PERMISSION_GRANTED -> {
                showPhotoSourceDialog()
            }
            else -> {
                cameraPermissionLauncher.launch(Manifest.permission.CAMERA)
            }
        }
    }

    private fun showPhotoSourceDialog() {
        val options = arrayOf("相机", "相册")
        AlertDialog.Builder(this)
            .setTitle("选择照片来源")
            .setItems(options) { _, which ->
                when (which) {
                    0 -> takePhoto()
                    1 -> chooseFromGallery()
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }

    private fun takePhoto() {
        val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        val photoFile = createImageFile()
        photoFile?.let {
            val photoURI = FileProvider.getUriForFile(
                this,
                "${packageName}.fileprovider",
                it
            )
            intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
            cameraLauncher.launch(intent)
        }
    }

    private fun chooseFromGallery() {
        val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        galleryLauncher.launch(intent)
    }

    private fun createImageFile(): File? {
        val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
        val storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
        return File.createTempFile(
            "JPEG_${timeStamp}_",
            ".jpg",
            storageDir
        ).apply {
            currentPhotoPath = absolutePath
        }
    }

    private fun saveAvatarToInternalStorage(bitmap: Bitmap): Boolean {
        return try {
            val file = File(filesDir, "avatar.jpg")
            val outputStream = FileOutputStream(file)
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, outputStream)
            outputStream.flush()
            outputStream.close()
            true
        } catch (e: Exception) {
            false
        }
    }

    private fun loadAvatarFromInternalStorage() {
        try {
            val file = File(filesDir, "avatar.jpg")
            if (file.exists()) {
                val bitmap = BitmapFactory.decodeFile(file.absolutePath)
                ivPlayerAvatar.setImageBitmap(bitmap)
            }
        } catch (e: Exception) {
            // 使用默认头像
        }
    }

    private fun setupBackPressHandler() {
        val onBackPressedCallback = object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                if (System.currentTimeMillis() - backPressedTime < 2000) {
                    finish()
                } else {
                    backPressedTime = System.currentTimeMillis()
                    Toast.makeText(this@MainActivity, "再按一次退出应用", Toast.LENGTH_SHORT).show()
                }
            }
        }
        onBackPressedDispatcher.addCallback(this, onBackPressedCallback)
    }

    private fun updatePlayerInfo() {
        tvPlayerName.text = playerName
        tvPlayerGender.text = playerGender
        tvPlayerPhone.text = playerPhone
        tvHighScore.text = highScore.toString()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        when (requestCode) {
            REQUEST_EDIT_INFO -> {
                if (resultCode == Activity.RESULT_OK && data != null) {
                    playerName = data.getStringExtra("name") ?: playerName
                    playerGender = data.getStringExtra("gender") ?: playerGender
                    playerPhone = data.getStringExtra("phone") ?: playerPhone
                    updatePlayerInfo()
                    Toast.makeText(this, "信息更新成功", Toast.LENGTH_SHORT).show()
                }
            }
            REQUEST_GAME -> {
                if (resultCode == Activity.RESULT_OK && data != null) {
                    val gameScore = data.getIntExtra("score", 0)
                    if (gameScore > highScore) {
                        highScore = gameScore
                        updatePlayerInfo()
                        Toast.makeText(this, "恭喜！新的最高分：$highScore", Toast.LENGTH_LONG).show()
                    }
                }
            }
        }
    }

    companion object {
        private const val REQUEST_EDIT_INFO = 1
        private const val REQUEST_GAME = 2
    }
}